﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetFrame;
using NetFrame.auto;
using MoneyProtocol;
using MoneyProtocol.dto;
using Server.tool;
using System.Data;

namespace Server.logic.login
{
    public class InOutHandler : AbsOnceHandler, HandlerInterface
    {
        cache.IAccountCache ac = cache.CacheFactory.accountCache;
        model.account_book accountBook = new model.account_book();
        model.pay_type payType = new model.pay_type();

        public void ClientClose(UserToken token, string error)
        {
        }

        public void MessageReceive(UserToken token, SocketModel message)
        {
            switch (message.command)
            {
                case InOutProtocol.ADD_CREQ:
                    addRecord(token, message.GetMessage<InOutInfoDTO>());
                    break;
                case InOutProtocol.UPDATE_CREQ:
                    updateRecord(token, message.GetMessage<InOutInfoDTO>());
                    break;
                case InOutProtocol.DELETE_CREQ:
                    deleteRecord(token, message.GetMessage<int[]>());
                    break;
                case InOutProtocol.GET_CREQ:
                    getRecordList(token, message.GetMessage<string>());
                    break;
            }
        }

        #region getRecord
        private void getRecordList(UserToken token, string date)
        {
            ExecutorPool.Instance.execute(
                    delegate ()
                    {
                        DateTime datetime = DateTime.Parse(date);
                        int user_id = ac.getId(token);

                        Console.WriteLine("ID为：" + user_id + "的用户进行获取收支记录列表操作");

                        write(token, InOutProtocol.GET_SRES, getList(user_id, datetime));
                    }
                    );
        }

        private List<InOutInfoDTO> getList(int user_id, DateTime dateTime)
        {
            DateTime dt;
            string strWhere = string.Format("`user_id`={0}", user_id);
            DataSet ds = accountBook.GetList(strWhere);
            List<InOutInfoDTO> list = new List<InOutInfoDTO>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                dt = DateTime.Parse(dr["o_date"].ToString());
                if (dt.Year == dateTime.Year && dt.Month == dateTime.Month)
                {
                    InOutInfoDTO data = new InOutInfoDTO();
                    data.id = int.Parse(dr["id"].ToString());
                    data.date = dt.ToString("yyyy/MM/dd");
                    data.price = float.Parse(dr["price"].ToString());
                    data.type = int.Parse(dr["type"].ToString());
                    data.typeinfo = translateTypeInfoIntToString(int.Parse(dr["type_info"].ToString()));
                    data.remark = dr["remark"].ToString();
                    list.Add(data);
                }
            }
            return list;
        }
        #endregion

        #region addRecord
        private void addRecord(UserToken token, InOutInfoDTO value)
        {
            ExecutorPool.Instance.execute(
                    delegate ()
                    {
                        int user_id = ac.getId(token);

                        Console.WriteLine("ID为：" + user_id + "的用户进行增加收支记录的操作");

                        updateAccoutBookObject(value, user_id);
                        int result;
                        if (accountBook.Add()) result = accountBook.GetMaxId();
                        else result = -1;
                        write(token, InOutProtocol.ADD_SRES, result);
                    }
                    );
        }
        #endregion

        #region updateRecord
        private void updateRecord(UserToken token, InOutInfoDTO value)
        {
            ExecutorPool.Instance.execute(
                    delegate ()
                    {
                        int user_id = ac.getId(token);

                        Console.WriteLine("ID为：" + user_id + "的用户进行修改收支记录的操作");

                        updateAccoutBookObject(value, user_id);
                        bool reslut = accountBook.Update();
                        write(token, InOutProtocol.UPDATE_SRES, reslut);
                    }
                    );
        }
        #endregion

        #region deleteRecord
        private void deleteRecord(UserToken token, int[] ids)
        {
            ExecutorPool.Instance.execute(
                    delegate ()
                    {
                        int result = 0;

                        Console.WriteLine("ID为：" + ac.getId(token) + "的用户进行删除收支记录的操作，需要删除" + ids.Length + "条记录");

                        foreach (int id in ids)
                        {
                            if (accountBook.Delete(id))
                                result++;
                        }

                        Console.WriteLine("已完成" + result + "记录的删除");

                        write(token, InOutProtocol.DELETE_SRES, result);
                    }
                    );
        }
        #endregion

        private void updateAccoutBookObject(InOutInfoDTO value, int user_id)
        {
            accountBook.id = value.id;
            accountBook.o_date = DateTime.Parse(value.date);
            accountBook.price = value.price;
            accountBook.type = value.type;
            accountBook.type_info = translateTypeInofStringToInt(value.typeinfo);
            accountBook.user_id = user_id;
            accountBook.remark = value.remark;
        }

        private int translateTypeInofStringToInt(string typeInfo)
        {
            string[] temp = typeInfo.Split('-');
            payType.GetIDFromName(temp[temp.Length - 1]);
            return payType.id;
        }

        private string translateTypeInfoIntToString(int typeInfo)
        {
            string result;
            payType.GetNameFromID(typeInfo);
            result = payType.name;
            while(payType.parent_id != 0)
            {
                payType.GetNameFromID(payType.parent_id);
                result += '-' + payType.name;
            }
            return result;
        }

        public override byte GetType()
        {
            return Protocol.TYPE_INOUT;
        }
    }
}
